package cn.hrc.config;

import cn.hrc.dao.BookMapper;
import cn.hrc.dao.FileMapper;
import cn.hrc.dao.HotMapper;
import cn.hrc.dao.TypeMapper;
import cn.hrc.entity.Book;
import cn.hrc.entity.Hot;
import cn.hrc.entity.LargeFile;
import cn.hrc.entity.Type;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class LoadConfig {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired // 轮播图
    HotMapper hotMapper;
    @Autowired // 商品
    BookMapper bookMapper;
    @Autowired // 图片
    FileMapper fileMapper;
    @Autowired
    TypeMapper typeMapper;
    @Autowired // Redis 缓存
    RedisTemplate redisTemplate;

    @PostConstruct
    public void initType(){
        logger.info("初始化类型");
        List<Type> types = typeMapper.selectByMap(null);
        for (Type type : types) {
            // 将类型数据放入redis中
            redisTemplate.opsForHash()
                    .put("hrc:type",type.getId(),type);
        }
        logger.info("初始化类型完成");
    }
    @PostConstruct// 在构造方法之后执行
    public void infoFile(){
        logger.info("初始化图片");
        List<LargeFile> files = fileMapper.findAll();
        for (LargeFile file : files) {
            // 将图片数据放入 Redis 中
            redisTemplate.opsForHash()
                    .put("hrc:file",file.getId(),file);
        }
        logger.info("初始化图片完成");
    }
    @PostConstruct// 在构造方法之后执行
    public void initHot(){
        logger.info("初始化轮播图");
        List<Hot> hots = hotMapper.selectByMap(null);
        for (Hot hot : hots) {
            // 将轮播图数据放入redis中
            redisTemplate.opsForHash()
                    .put("hrc:hot",hot.getId(),hot);
        }
        logger.info("初始化轮播图完成");
    }
    @PostConstruct // 在构造方法之后执行
    public void initBook(){
        logger.info("初始化书籍");
        List<Book> books = bookMapper.selectByMap(null);

        for (Book book : books) {
            // 将书籍数据放入redis中
            redisTemplate.opsForHash()
                    .put("hrc:book",book.getId(),book);
            redisTemplate.opsForZSet()
                    .add("book",book,book.getSalenum());
        }
        logger.info("初始化书籍完成");
    }
}
